﻿// Copyright (c) 2009, 3G.cn
// $Author: Moweiqiang $
// $Date: 09-02-03 17:49 $
// $Revision: 4 $
// $NoKeywords: $
namespace Jiubang.Util {
	using System;
	using System.Data;
	using System.IO;
	using System.Text.RegularExpressions;
	using System.Web;

	/// <summary>
	/// UBB转换类
	/// </summary>
	public class Ubb : IDisposable {
		private readonly DataTable ubbTable;

		///<summary>
		/// 文件不存在时将自动生成一个文件
		/// </summary>
		/// <param name="filepath">如果指定路径为空则默认为~/App_Data/ubb.xml</param>
		public Ubb(string filepath) {
			if (string.IsNullOrEmpty(filepath))
				filepath = HttpContext.Current.Server.MapPath("~/App_Data/ubb.xml");
			ubbTable = new DataTable("ubb");
			ubbTable.Columns.Add("name", typeof (string));
			ubbTable.Columns.Add("ubb", typeof (string));
			ubbTable.Columns.Add("code", typeof (string));
			ubbTable.Columns.Add("prority", typeof (int));

			if (!File.Exists(filepath)) {
				//创建常用对象
				DataRow row = ubbTable.NewRow();
				row["name"] = "链接";
				row["ubb"] = @"\[URL=(.+?)\](.+?)\[/URL\]";
				row["code"] = "<a href=\"$1\">$2</a>";
				row["prority"] = 1;
				ubbTable.Rows.Add(row);

				row = ubbTable.NewRow();
				row["name"] = "图片";
				row["ubb"] = @"\[IMG=(.+?)\]";
				row["code"] = "<img src='$1' alt='.'/>";
				row["prority"] = 0;
				ubbTable.Rows.Add(row);

				ubbTable.WriteXml(filepath);
			} else {
				ubbTable.ReadXml(filepath);
				ubbTable.DefaultView.Sort = "prority";
			}
		}


		/// <summary>
		/// 以单行模式翻译UBB代码
		/// </summary>
		/// <param name="content"></param>
		/// <returns></returns>
		public string Interpret(string content) {
			foreach (DataRowView row in ubbTable.DefaultView)
				content = Regex.Replace(content, (string) row["ubb"], (string) row["code"], RegexOptions.Singleline | RegexOptions.Compiled);
			return content;
		}

		#region IDisposable 成员

		/// <summary>
		/// 调用DataTable的Dispose方法
		/// </summary>
		public void Dispose() { ubbTable.Dispose(); }

		#endregion
	}
}